/*
 * Copyright (c) 2017. danlu.com Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.dlware.global;

import android.text.TextUtils;

import com.danlu.lib.net.callback.ITokenRetryCallback;
import com.danlu.lib.net.constant.HttpCode;
import com.danlu.lib.net.creator.RetrofitCreator;
import com.umeng.analytics.MobclickAgent;
import com.yiji.www.paymentcenter.YijiPayPlugin;

import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.BuildConfig;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.api.DanluApi;
import cn.com.dhc.danlu.dlware.api.MsgApi;
import cn.com.dhc.danlu.model.CategoryModel;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.PreferenceUtils;
import cn.com.dhc.danlu.util.PushEngine;
import cn.com.dhc.danlu.util.SerializeCache;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BasePageRequest;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.freedom.response.base.BaseResponseWrapper;
import cn.com.hd.mall.web.webservices.entity.request.login.LoginRequest;
import cn.com.hd.mall.web.webservices.entity.response.login.LoginResponse;
import cn.com.hd.mall.web.webservices.entity.response.merch.CategoryListResponse;
import rx.Observable;

/**
 * author: wuhaiyang(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-02-07 下午3:51<br/>
 * <p>
 * 全局application代理 监听器
 * 全局变量 | 全局方法，app内共享,
 * ps: 尽可能少在application中存放全局变量，很容易被系统释放
 * </p>
 * <p>
 * fixme:后期最好定义接口的形式外排方法
 */
public class GlobalApiAgent implements ITokenRetryCallback {
    /**
     * 登录用户信息
     */
    private LoginResponse loginResponse;
    /**
     * 用户角色信息
     */
    private int roleCode;
    /**
     * 会话验证标识
     */
    private String token;
    /**
     * 是否为终端店角色
     */
    private boolean isTerminalRole;
    private boolean isWifi;
    private List<CategoryModel> allCategory;
    private String fromTag;

    private DanluApi danluApi;
    private MsgApi msgApi;

    public void onCreate() {
        // 初始化推送业务相关 release前请置为false
        PushEngine.newInstance().registerPush();
        // 易极付初始化
        YijiPayPlugin.init(DanluApplication.get());
        // 易极付测试环境
        //        YijiPayPlugin.setEnv(YijiPayPlugin.ENV_SNET);
        //易极付生产
        YijiPayPlugin.setEnv(YijiPayPlugin.ENV_RELEASE);
        // 引入switchHost 可能需要 改变此方法调用时机
        initApi();

        initUmeng();
    }

    private void initUmeng() {
        //设置普通统计场景类型
        MobclickAgent.setScenarioType(DanluApplication.get(), MobclickAgent.EScenarioType.E_UM_NORMAL);
    }

    private void initApi() {
        if (null != msgApi && null != danluApi) {
            return;
        }
        msgApi = new RetrofitCreator<MsgApi>()
                .baseUrl(BuildConfig.msgcenter_url)
                .interfaceApi(MsgApi.class)
                .setCallback(this)
                .isLogData(false)
                .buildService();
        danluApi = new RetrofitCreator<DanluApi>()
                .baseUrl(BuildConfig.webservice_url)
                .interfaceApi(DanluApi.class)
                .setCallback(this)
                .isLogData(false)
                .buildService();
    }

    public LoginResponse getLoginUser() {
        if (null != loginResponse) {
            return loginResponse;
        } else {
            return SerializeCache.getInstance().getResponse();
        }
    }

    public void setLoginUser(LoginResponse loginResponse) {
        this.loginResponse = loginResponse;
        this.token = loginResponse.getToken();
        // 用户ID
        final String roleID = loginResponse.getUserId();
        this.roleCode = CommonUtils.getRole(loginResponse.getUserRole());
        this.isTerminalRole = CommonUtils.isTerminalRole(loginResponse.getUserRole());

        //保存到全局变量缓存中
        SerializeCache.getInstance().saveResponse(loginResponse);
        SerializeCache.getInstance().saveToken(token);
        SerializeCache.getInstance().saveRoleId(roleID);
        SerializeCache.getInstance().saveRoleCode(roleCode);
        SerializeCache.getInstance().saveIsTerminal(isTerminalRole);
        SerializeCache.getInstance().saveSessionId(loginResponse.getSessionId());
    }

    public String getSessionId() {
        return SerializeCache.getInstance().getSessionId();
    }

    public List<CategoryModel> getAllCategory() {
        return allCategory;
    }

    public void setAllCategory(CategoryListResponse categoryListResponse) {
        if (allCategory == null) {
            allCategory = new ArrayList<>();
        } else {
            allCategory.clear();
        }
        for (CategoryListResponse.CategoryItem categoryItem : categoryListResponse.categoryList) {
            CategoryModel categoryModel = new CategoryModel();
            categoryModel.name = categoryItem.categoryName;
            categoryModel.code = categoryItem.categoryCode;

            ArrayList<CategoryModel> childs = new ArrayList<>();
            for (CategoryListResponse.CategoryItem categoryChildrenItem : categoryItem.children) {
                CategoryModel childCategoryModel = new CategoryModel();
                childCategoryModel.name = categoryChildrenItem.categoryName;
                childCategoryModel.code = categoryChildrenItem.categoryCode;
                childCategoryModel.iconURL = categoryListResponse.baseImgStr + categoryChildrenItem.categoryUrl;
                childs.add(childCategoryModel);
            }
            categoryModel.categoryModels = childs;
            allCategory.add(categoryModel);
        }
    }

    public CategoryModel getCategory(int categoryIndex) {
        return allCategory.get(categoryIndex);
    }

    public CategoryModel getCategory(int categoryIndex, int subCategoryIndex) {
        if (null != allCategory && null != allCategory.get(categoryIndex) && null != allCategory.get(categoryIndex).getChildrens()) {
            return allCategory.get(categoryIndex).getChildrens().get(subCategoryIndex);
        } else {
            return null;
        }
    }


    public boolean isTerminalRole() {
        return SerializeCache.getInstance().isTerminalRole();
    }

    /**
     * 注销时清理登录用户信息
     */
    public void clearLoginUser() {
        this.loginResponse = null;
        this.token = null;
        this.roleCode = 0;
        this.isTerminalRole = false;

        SerializeCache.getInstance().clear();
    }

    public boolean isWifi() {
        return isWifi;
    }

    public void setWifi(boolean wifi) {
        isWifi = wifi;
    }

    public String getRoleID() {
        return SerializeCache.getInstance().getRoleId();
    }

    public String getFromTag() {
        return fromTag;
    }

    public void setFromTag(String fromTag) {
        this.fromTag = fromTag;
    }

    public DanluApi getApi() {
        return danluApi;
    }

    public MsgApi getMsgApi() {
        return msgApi;
    }

    @Override
    public void resetToken(Object o) {
        String token = getToken();
        if (o instanceof BaseRequest) {
            BaseRequest req = (BaseRequest) o;
            req.setToken(token);
        } else if (o instanceof cn.com.hd.mall.web.webservices.entity.BaseRequest) {
            cn.com.hd.mall.web.webservices.entity.BaseRequest req = (cn.com.hd.mall.web.webservices.entity.BaseRequest) o;
            req.setToken(token);
        } else if (o instanceof BasePageRequest) {
            BasePageRequest req = (BasePageRequest) o;
            req.setToken(token);
        }
    }

    @Override
    public Observable createRefreshObservable() {
        PreferenceUtils utils = new PreferenceUtils(DanluApplication.get());
        // 获取储存的用户名与密码
        String loginName = TextUtils.isEmpty(utils.getLoginName()) ? "loginName" : utils.getLoginName();
        String password = TextUtils.isEmpty(utils.getPassword()) ? "pwd" : utils.getPassword();
        LoginRequest request = new LoginRequest();
        request.setUsername(loginName);
        request.setPassword(password);
        return getApi().login(request).compose(OperatorUtils.<LoginResponse> defaultSchedulers());
    }

    @Override
    public boolean judgeTokenIsGetSuc(Object o) {
        if (null != o && o instanceof LoginResponse && ((LoginResponse) o).getSuccess().equals("0")) {
            setLoginUser((LoginResponse) o);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean isApiReqSuc(Object obj) {
        if (null != obj && obj instanceof BaseResponseWrapper) {
            BaseResponseWrapper wrapper = (BaseResponseWrapper) obj;
            if (wrapper.getModel() instanceof LoginResponse) {
                return false;
            }
            BaseResponseWrapper res = (BaseResponseWrapper) obj;
            return res.getCode() == HttpCode.SUCCESS;
        }
        return false;
    }

    @Override
    public void refreshTokenError() {
        // 跳转到登陆页面，用户手动进行登陆
        CommonUtils.exitCleanAction(DanluApplication.get());
    }

    @Override
    public String getToken() {
        if (!TextUtils.isEmpty(token)) {
            return token;
        } else {
            return SerializeCache.getInstance().getToken();
        }
    }

}
